package pers.xx.sbm.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author ：xiexing
 * @description：文件操作类 导入、导出等
 * @date ：2020/12/10 9:23
 */
public class ExportExcelUtils {

    /**
     * @param data        导出数据
     * @param columnNames 表头
     * @param fileName    文件名称
     * @param title       excel表格标题
     * @description 导出excel
     * @author XieXing
     * @date 2020/12/10 10:22
     */

    public static void exportExcel(List<Object[]> data, String[] columnNames, String fileName, String title) throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        // 每次写100行数据，就刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory,
        Sheet sh = wb.createSheet();
        Row row = sh.createRow(0);
        // 第一行设置标题
        for (int i = 0; i < columnNames.length; i++) {
            String column = columnNames[i];
            Cell cell1 = row.createCell(i);
            cell1.setCellValue(column);
        }
        // 导出数据
        for (int rowNum = 0; rowNum < data.size(); rowNum++) {
            Row rowData = sh.createRow(rowNum + 1);
            Object[] tmp = data.get(rowNum);
            for (int j = 0; j < tmp.length; j++) {
                Cell cell = rowData.createCell(j);
                cell.setCellValue(tmp[j].toString());
            }
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
        wb.write(response.getOutputStream());
        wb.close();
    }


}
